import os

# 复制视频到指定文件夹
def copy_video(new_file_path,file_path):
    dir_names = os.listdir(new_file_path)
    for dir_name in dir_names:
        file_name = file_path[file_path.rfind("/") + 1:]
        if file_name.find(dir_name, 0, len(file_path)) > 0 and not dir_name.find(".mp4", 0, len(dir_name)) > 0:
            print("copy_video dir_name:" + dir_name)
            new_file = os.path.join(new_file_path, dir_name, file_name)
            print("copy_video new_file:" + file_path + " to " + new_file)
            if not os.path.exists(new_file):
                file = open(file_path, "rb")
                with open(new_file, "wb+") as ff:
                    ff.write(file.read())
                    file.close()
                    os.remove(file_path)
                with open(new_file_path + "/copied.log", "a+", encoding='utf-8') as cc:
                    cc.write(file_path + "\n")
            else:
                os.remove(file_path)

def copy_other_video(new_file_path, old_file_path):
    file_name = old_file_path[old_file_path.rfind("/") + 1:]
    new_file = os.path.join(new_file_path, "/", file_name)
    print("copy_other_video:" + old_file_path + " to " + new_file)
    if not os.path.exists(new_file):
        file = open(old_file_path, "rb")
        with open(new_file, "wb+") as ff:
            ff.write(file.read())
            file.close()
            os.remove(old_file_path)
        with open(new_file_path + "/copied.log", "a+", encoding='utf-8') as cc:
            cc.write(old_file_path + "\n")
    else:
        os.remove(old_file_path)

def get_all_file_path(file_path):
    if os.path.exists("E:/videopath.txt"):
        os.remove("E:/videopath.txt")
    for dirpath, dirnames, filenames in os.walk(file_path):
        for filename in filenames:
            filename = dirpath.replace("\\", "/") + '/' + filename
            print("get_all_file_path:" + filename)
            if filename.find(".mp4") > 0:
                with open("E:/videopath.txt", "a+", encoding='utf-8') as vv:
                    vv.write(filename + "\n")


if __name__ == '__main__':
    # 源文件夹
    get_all_file_path(r'D:\bilibilivideobypy')
    videofile = open("E:/videopath.txt", encoding="utf-8")
    for videopath in videofile:
        try:
            videopath = videopath.split("\n")[0]
            print(videopath)
            copy_video('D:/videobypy',videopath)
            # copy_other_video("E:/videobypy", videopath)
        except RuntimeError as rte:
            print(rte)
            continue
